package com.kkb.cubemall.product.exception;

import com.kkb.cubemall.common.exception.CubemallEnum;
import com.kkb.cubemall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LiJun
 * @date 2021/5/25 21:38
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.kkb.cubemall.product.controller")
public class CubemallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("检验数据出现问题{},异常类型{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach((fieldError -> {
            String field = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            map.put(field, message);
        }));
        return R.error(CubemallEnum.VALID_EXCEPTION.getCode(), CubemallEnum.VALID_EXCEPTION.getMessage()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleValidException(Throwable throwable) {
        log.error("未知异常", throwable);
        return R.error(CubemallEnum.UNKNOWN_EXCEPTION.getCode(), CubemallEnum.UNKNOWN_EXCEPTION.getMessage()).put("data", "未知异常");
    }
}
